/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief This is an example for using the MaCICtrl interface.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: MaCICtrlClientExample.cpp,v 1.4 2009-05-13 07:18:15 amaula Exp $
 *
 */
#include "MaCICtrlClient.hpp"

//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************

//*****************************************************************************
enum EMode { KModeDebug = 0, KModeSLScan = 1 };
//*****************************************************************************
static int verbose = 1;
static int mode = KModeSLScan;
static unsigned char authkey[16] = "r6oZE93Ba1Q6KKn";

//*****************************************************************************
using namespace MaCI::MaCICtrl;
//*****************************************************************************

void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tMaCICtrlClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tUse 'name' as MaCICtrl target\n");

  fprintf(stderr,"  [-M mode]\t\t\tQuery mode to use. Default is 'debug'. Others: 'slscan'\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

void DoDebug(MaCI::MaCICtrl::CMaCICtrlClient &mcc)
{
  
  MaCI::EMaCIError e;

  dPrint(1,"Succesfully opened MaCICtrlClient, running service Discovery");
  gimi::t_serviceList servicelist;
  mcc.DiscoverMaCICtrlServices(servicelist, 5000);
  dPrint(1,"Got %u MaCICtrl compliant services", servicelist.size());
      
      
  dPrint(1,"Requesting information of ALL services using the ServiceList handling function.");
  TServiceEntryArray entries;
  if (mcc.GetServiceArray(entries, servicelist) == MaCI::KMaCIOK) {
    dPrint(1,"Got %d Entries of information:", entries.size());
    for(EACH_IN_i(entries)) {
      i->Print(1);
    }
        
  } else {
    dPrint(1,"Failed to query information for Entries!");
        
  }

  const std::string macisl("Dummy.Dummy.Dummy");
  dPrint(1,"\n\n\nTesting Filtering using MaCISL '%s", macisl.c_str());
  TServiceEntryArray filteredentries;
  mcc.FilterServices(filteredentries, entries, macisl);
  dPrint(1,"After filtering got %u Service entires:", filteredentries.size());
  for(EACH_IN_i(filteredentries)) {
    i->Print(1);
  }

  dPrint(1,"Acquiring access for all services... (With key: 'r6oZE93Ba1Q6KKn')");
  const TAuthentication auth(authkey, sizeof(authkey));
  TAccess acc;

  // Loop through all services.
  for(EACH_IN_i(filteredentries)) {
    const TService &service = i->service;
    dPrint(1,"Selecting target service %u:%u from client: '%s'",
           service.servicemajor, service.serviceminor, i->gimnetname.c_str());
    e = mcc.RequestAuthentication(i->gimnetname,
                                  service.servicemajor, service.serviceminor,
                                  auth,
                                  acc);
    if (e == MaCI::KMaCIOK) {
      dPrint(1,"Succesfully requested authentication for client: '%s' for service %u:%u",
             i->gimnetname.c_str(), service.servicemajor, service.serviceminor);
      dPrint(1,"Access mask for Client: '%s' is: Access: %s",
             i->gimnetname.c_str(),
             acc.IsAccess()? "allow" : "deny");
          
    } else {
      dPrint(1,"Failed to Request authentication to client: '%s' for service %u:%u (%d:%s)",
             i->gimnetname.c_str(), service.servicemajor, service.serviceminor, e, GetErrorStr(e).c_str());
          
    }
  }

}
//*****************************************************************************

void DoSLScan(MaCI::MaCICtrl::CMaCICtrlClient &mcc)
{  
  dPrint(1,"Running service Discovery");
  gimi::t_serviceList servicelist;
  mcc.DiscoverMaCICtrlServices(servicelist, 3000);
  dPrint(1,"Got %u MaCICtrl compliant services", servicelist.size());
      
  dPrint(1,"Requesting information of ALL services using the ServiceList handling function.");
  TServiceEntryArray entries;
  if (mcc.GetServiceArray(entries, servicelist, 5000) == MaCI::KMaCIOK) {
    dPrint(1,"Got %d Entries of information, printing unique entries:", entries.size());
    std::string lastsl;
    for(EACH_IN_i(entries)) {
      const std::string currentsl = i->GetMaCISL().ToMaCISLString();
      
      if (currentsl != lastsl) {
        dPrintLCGreen(1,"'%s' @ MaCISL:\t'%s'", 
               i->gimnetname.c_str(),
               currentsl.c_str());
        lastsl = currentsl;
      }
    }
        
  } else {
    dPrint(1,"Failed to query information for Entries!");
        
  }
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  
  // GIMnet parameters
  std::string gimnetAP = "localhost";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";

  // Objects
  //  bool run = true;
  gimi::GIMI g;
  MaCI::MaCICtrl::CMaCICtrlClient mcc(&g, -1);

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(1);
  debugSetLogFilename("MaCICtrlClientExample.log");

  // Greet
  fprintf(stderr,
	  "\nMaCICtrlClientExample - MaCICtrl Client Interface Example - $Revision: 1.4 $\n\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "M:K:s:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////
    case 'M':
      if (optarg == std::string("slscan")) {
        mode = KModeSLScan;
        dPrint(3,"Using mode: 'SLScan'");
      } else if (optarg == std::string("debug")) {
        mode = KModeDebug;
        dPrint(3,"Using mode: 'Debug'");
      }
      break;

    case 'K':
      strncpy((char*)authkey, optarg, sizeof(authkey));
      authkey[(sizeof(authkey)-1)] = 0;
      dPrint(3,"Using AuthorizationKey '%s'", authkey);
      break;

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 's':
      gimnetSourceName = optarg;
      dPrint(3,"Using GIMnet source name '%s'", optarg);
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }

  /*
  ///////////////  // JUST TESTING
  SMaCISL msl;
  msl.FromMaCISL("Foo.bar.zaa.zoo.zii.MaCI_Alarm.MunInstance");
  dPrint(ODTEST, "Group: '%s'", msl.group.c_str());
  dPrint(ODTEST, "Interface: '%s'", msl.interface.c_str());
  dPrint(ODTEST, "Instance: '%s'", msl.instance.c_str());
  exit(666);
  /////////////////////
  */
  MaCI::EMaCIError e;
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    ownSleep_ms(500);

    // Attempt to Open Client
    if ( (e = mcc.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open MaCICtrlClient instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {

      // Now execute test.
      switch(mode) {
      case KModeDebug:
        DoDebug(mcc);
        break;

      case KModeSLScan:
        DoSLScan(mcc);
        break;
      }
    }
  }
  
  dPrint(1,"MaCICtrlClientExample completed.");
  
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

